package servlet.login;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.User;
import service.LoginService;

/**
 * 登录检查
 * 
 * @author 崔诗新
 */
@SuppressWarnings("serial")
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	
    public LoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String errorInfo = "对不起，您输入的用户名或密码不正确！";
		
		String operation = request.getParameter("operation");
		if (operation != null && operation.equals("logout")) {
			request.getSession().removeAttribute("isLogin");
			request.getSession().removeAttribute("username");
			request.getSession().removeAttribute("power");
			response.getWriter().write("<script>top.window.location='"+request.getContextPath()+"/login.jsp'</script>");
			return;
		}
		
		LoginService service = new LoginService();
		User user = service.getUser(username, password);
		if (user != null) {
			request.getSession().setAttribute("isLogin", true);
			request.getSession().setAttribute("username", username);
			request.getSession().setAttribute("power", user.getPower());
			if (user.getPower().equals("0"))
				response.sendRedirect(request.getContextPath() + "/admin/index.jsp");
			else if(user.getPower().equals("1"))
				request.getRequestDispatcher("/index.jsp").forward(request, response);
		}
		else {
			request.setAttribute("errorInfo", errorInfo);
			request.getRequestDispatcher("/error.jsp").forward(request, response);
		}
	}
}
